package com.ztf.gui;

import com.ztf.bean.Message;
import com.ztf.bean.User;

import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.SwingConstants;

/**
 * 聊天消息
 */
public class MsgCellRender extends DefaultListCellRenderer {
	private static final long serialVersionUID = 1L;
	static List<String> msgs = new ArrayList<>();

	@Override
	public Component getListCellRendererComponent(JList<? extends Object> list,
			Object value, int index, boolean isSelected, boolean cellHasFocus){
		//instanceof 判断其左边对象是否为其右边类的实例
		if(value instanceof Message){
			Message msg = (Message) value;
			User from = msg.getFrom();
			try{
				if(!from.equals(ChatRoom.userNow)) {
					String info=from.getName()+" "+msg.getTime();

					//a.这里可以用html来控制字体的颜色
					String text1 = "<html><body width=\"520px\"><div color=\"blue\" align=\"left\">"+info+"</div><div color=\"black\" align=\"left\">"+msg.getContent()+"</div></body></html>";
					//b.也可以通过设置前景色来改变字体颜色
					setForeground(Color.blue);
					setText(text1);
					//设置背景色
					setBackground(Color.white);
					//设置文本的水平和垂直位置:比如（右上）
					setVerticalTextPosition(SwingConstants.TOP);
					setHorizontalTextPosition(SwingConstants.RIGHT);

					InputStream is = new ByteArrayInputStream(from.getHead());
					BufferedImage image = ImageIO.read(is);
					setIcon(new ImageIcon(image));

				}else {
					String info=from.getName()+" "+msg.getTime();

					//a.这里可以用html来控制字体的颜色
					String text1 = "<html><body width=\"520px\"><div color=\"blue\" align=\"right\">"+info+"</div><div color=\"black\" align=\"right\">"+msg.getContent()+"</div></body></html>";
					//b.也可以通过设置前景色来改变字体颜色
					setForeground(Color.blue);
					setText(text1);
					//设置背景色
					setBackground(Color.white);
					//设置文本的水平和垂直位置:比如（右上）
					setVerticalTextPosition(SwingConstants.TOP);
					setHorizontalTextPosition(SwingConstants.LEFT);

					InputStream is = new ByteArrayInputStream(from.getHead());
					BufferedImage image = ImageIO.read(is);
					setIcon(new ImageIcon(image));

					setLayout(new FlowLayout());
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		if(isSelected){

		}

		return this;
	}
}